'''
Descripttion: 
Author: Cxy
Date: 2022-08-27 00:49:00
LastEditors: Cxy
LastEditTime: 2022-08-30 13:06:44
FilePath: \ehomes-admind:\giteeBlog\blogServe\face\faceRecognition.py
'''
import json
import cv2 as cv
from glob import *
import sys
import base64
import numpy as np


def executionProcedure():
    lines = sys.stdin.readlines()[0]
    reqParams = json.loads(lines)
    faceSplit = reqParams['faceImgBase64'].split(',')[1]
    # base64解码图片
    faceImg = base64.b64decode(faceSplit)
    # 将faceImg以流的形式读入转化成ndarray对象
    nparr = np.frombuffer(faceImg, np.uint8)
    # 从指定的内存缓存中读取数据，并把数据转换(解码)成图像格式；主要用于从网络传输数据中恢复出图像
    faceNp = cv.imdecode(nparr, cv.IMREAD_COLOR)
    # 创建人脸模型
    recogizer = cv.face.LBPHFaceRecognizer_create()
    facePath = reqParams['facePath']
    faceModelPath = facePath + '/faceModel.yml'
    # 加载人脸数据库
    recogizer.read(faceModelPath)

    # 人脸检测方法
    def face_detect(frame):
        # 灰度转换
        gray_a = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
        face_Model = cv.CascadeClassifier(
            facePath + '/model/haarcascade_frontalface_default.xml')
        # detectMultiScale(图片，缩放倍数，检测次数, 不用管，人脸最小，人脸最大)
        # face = face_Model.detectMultiScale(gray_a, 1.01, 5, 0, (300, 300), (500, 500))
        face = face_Model.detectMultiScale(gray_a)
        if len(face) == 0:
            return print(json.dumps({'code': 401}))
        for x, y, w, h in face:
            # 人脸识别
            ids, confidence = recogizer.predict(gray_a[y:y + h, x:x + w])
            if confidence > 80:
                print(json.dumps({'code': 400}))
            else:
                print(json.dumps({'code': 200, 'id': ids}))

    face_detect(faceNp)
    sys.stdout.flush()
    cv.destroyAllWindows()


# 调取主程序文件传递参数 因使用click模块不能直接拿到参数
if __name__ == '__main__':
    executionProcedure()

# 给node传递值
# print('我是传递给node的值', flush=True)

# print('我是传递给node的值')
# sys.stdout.flush()
